package dp05.leertaak1.dao.implementations;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

import dp05.leertaak1.dao.definitions.DAO;

public class RdbDAO extends DAO
{

    public final String USER = "root";
    public final String PASS = "root";
    public final String URL = "jdbc:mysql://localhost:3306/dp05";

    private Connection con;
    private Statement stmt;
    private int dsSize = 0;

    private RdbDAO()
    {
        super();
        try
        {
            con = DriverManager.getConnection(URL, USER, PASS);
        } catch (SQLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static DAO getInstance()
    {
        if (instance == null)
        {
            synchronized (RdbDAO.class)
            {
                if (instance == null)
                {
                    instance = new RdbDAO();
                }
            }
        }
        return instance;
    }

    @Override
    public LinkedList<Integer> get()
    {
        dataStructure.clear();
        try
        {
            stmt = con.createStatement();
            stmt.execute("SELECT * FROM `getallen`");
            ResultSet rs = stmt.getResultSet();
            while (rs.next())
            {
                dataStructure.add(rs.getInt("getal"));
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        dsSize = dataStructure.size();
        return dataStructure;
    }

    @Override
    public void update()
    {
        if (dataStructure == null || dataStructure.size() == 0 || dataStructure.size() == dsSize)
        {
            System.out.println("There is no data to update");
        } else
        {
            try
            {
                stmt = con.createStatement();
                StringBuilder sql = new StringBuilder();
                sql.append("INSERT INTO getallen VALUES");
                for (int i = dsSize; i < dataStructure.size(); i++)
                {
                    if (i > dsSize)
                    {
                        sql.append(",");
                    }
                    sql.append("(" + dataStructure.get(i) + ")");
                }
                System.out.println(sql);
                stmt.execute(sql.toString());
                dsSize = dataStructure.size();
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }

    }

}
